package com.train.mgr.modules.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.train.common.enums.PublishEnum;
import com.train.common.exception.BizException;
import com.train.common.utils.AuthUtils;
import com.train.common.utils.StringUtils;
import com.train.mgr.modules.biz.dto.request.LessonReqDTO;
import com.train.mgr.modules.biz.dto.response.LessonDetailRespDTO;
import com.train.mgr.modules.biz.dto.response.LessonListRespDTO;
import com.train.mgr.modules.biz.entity.Course;
import com.train.mgr.modules.biz.entity.Lesson;
import com.train.mgr.modules.biz.entity.LessonLessonRole;
import com.train.mgr.modules.biz.entity.LessonRole;
import com.train.mgr.modules.biz.mapper.CourseMapper;
import com.train.mgr.modules.biz.mapper.LessonLessonRoleMapper;
import com.train.mgr.modules.biz.mapper.LessonMapper;
import com.train.mgr.modules.biz.mapper.LessonRoleMapper;
import com.train.mgr.modules.biz.service.ILessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课时表 服务实现类
 * </p>
 *
 * @author cxg
 * @date 2025-09-30
 */
@Slf4j
@RequiredArgsConstructor
@Service("ILessonService")
public class LessonServiceImpl extends ServiceImpl<LessonMapper, Lesson> implements ILessonService {

    private final CourseMapper courseMapper;

    private final LessonLessonRoleMapper lessonLessonRoleMapper;

    private final LessonRoleMapper lessonRoleMapper;


    @Override
    public int delByCoursId(Long coursId){
       return baseMapper.delByCoursId(coursId);
    }

    @Override
    public LessonDetailRespDTO getDetailById(Long lessonId){
        Lesson lessonBean = baseMapper.selectById(lessonId);
        if(ObjectUtil.isEmpty(lessonBean)){
            throw new BizException("课时不存在");
        }
        LessonDetailRespDTO dto = new LessonDetailRespDTO();
        BeanUtil.copyProperties(lessonBean, dto);

        try{
            if(StringUtils.isNotEmpty(lessonBean.getSalesLanguage())){
                dto.setSalesLanguageMap(new ObjectMapper().readValue(lessonBean.getSalesLanguage(), Map.class));
            }
            if(StringUtils.isNotEmpty(lessonBean.getPassingScore())){
                dto.setPassingScoreMap(new ObjectMapper().readValue(lessonBean.getPassingScore(), Map.class));
            }
        }catch (Exception ex){
            log.error("ObjectMapper error",ex);
        }

        LambdaQueryWrapper<LessonLessonRole> wrapper = Wrappers.<LessonLessonRole>lambdaQuery()
                .eq(LessonLessonRole::getLessonId, lessonId)
                .eq(LessonLessonRole::getCustomerId, lessonBean.getCustomerId())
                .eq(LessonLessonRole::getIsDeleted, 0);
        List<LessonLessonRole> roleList = lessonLessonRoleMapper.selectList(wrapper);
        if(ObjectUtil.isNotEmpty(roleList)){
            List<LessonDetailRespDTO.roleItem> roleSelectList = new ArrayList<>();
            for(int i=0;i<roleList.size();i++){
                LessonLessonRole roleBean = roleList.get(i);
                Long lessonRoleId = roleBean.getLessonRoleId();
                LessonRole baseRoleBean = lessonRoleMapper.selectById(lessonRoleId);
                LessonDetailRespDTO.roleItem roleItem =new LessonDetailRespDTO.roleItem();
                roleItem.setBackgroundInformation(baseRoleBean.getBackgroundInformation());
                roleItem.setCustomerId(baseRoleBean.getCustomerId());
                roleItem.setRoleDefinition(baseRoleBean.getRoleDefinition());
                roleItem.setRoleId(baseRoleBean.getId());
                roleItem.setRoleName(baseRoleBean.getRoleName());
                roleItem.setSex(baseRoleBean.getSex());
                roleSelectList.add(roleItem);
            }
            dto.setRoleSelectList(roleSelectList);
        }
        return dto;
    }

    @Override
    @Transactional
    public boolean add(LessonReqDTO body){
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        this.checkByLessonName(body.getLessonName(),body.getId());

        Course course = courseMapper.selectById(body.getCourseId());
        if(ObjectUtil.isEmpty(course)){
            throw new BizException("课程不存在");
        }

        Lesson bean = BeanUtil.copyProperties(body, Lesson.class);
      //  Long lessonOrder = this.getLessonCount(customerId,body.getCourseId());
        bean.setLessonOrder(0);//序号--不由后端控制
        bean.setCustomerId(customerId);
        bean.setCourseName(course.getCourseName());
        bean.setSalesLanguage(JSONObject.toJSONString(body.getSalesLanguage()));
        bean.setPassingScore(JSONObject.toJSONString(body.getPassingScore()));
        bean.setCreateBy(AuthUtils.getCurrentUser().getNickName());
        bean.setIsPublish(PublishEnum.UN_PUBLIC.getCode());
        int rows = baseMapper.insert(bean);
        long lessonId = bean.getId();
        if(rows > 0 && body.getRoleSelectList()!=null && body.getRoleSelectList().size() >0){
            //保存角色定义关系
            List<Long> roleIds =  body.getRoleSelectList();
            roleIds.forEach(roleId -> {
                LessonLessonRole roleBean = new LessonLessonRole();
                roleBean.setLessonId(lessonId);
                roleBean.setCustomerId(customerId);
                roleBean.setLessonRoleId(roleId);
                lessonLessonRoleMapper.insert(roleBean);
            });
        }
        boolean bool = rows >0 ? true : false;
        return bool;
    }

    @Override
    @Transactional
    public boolean update(LessonReqDTO body) {
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        this.checkByLessonName(body.getLessonName(), body.getId());
        Course course = courseMapper.selectById(body.getCourseId());
        if(ObjectUtil.isEmpty(course)){
            throw new BizException("课程不存在");
        }

        Lesson lessonBean = baseMapper.selectById(body.getId());
        if(ObjectUtil.isEmpty(lessonBean)){
            throw new BizException("课时不存在");
        }
        BeanUtil.copyProperties(body, lessonBean);
        lessonBean.setSalesLanguage(JSONObject.toJSONString(body.getSalesLanguage()));
        lessonBean.setPassingScore(JSONObject.toJSONString(body.getPassingScore()));
        lessonBean.setUpdateBy(AuthUtils.getCurrentUser().getNickName());
        int rows = baseMapper.updateById(lessonBean);
        long lessonId = body.getId();
        if(rows > 0 && body.getRoleSelectList()!=null && body.getRoleSelectList().size() >0){
            //先做清空处理
            lessonLessonRoleMapper.deleteByLessonId(lessonId,customerId);
            //保存角色定义关系
            List<Long> roleIds =  body.getRoleSelectList();
            roleIds.forEach(roleId -> {
                LessonLessonRole roleBean = new LessonLessonRole();
                roleBean.setLessonId(lessonId);
                roleBean.setCustomerId(customerId);
                roleBean.setLessonRoleId(roleId);
                lessonLessonRoleMapper.insert(roleBean);
            });
        }else{
            lessonLessonRoleMapper.deleteByLessonId(lessonId,customerId);
        }
        boolean bool = rows >0 ? true : false;
        return bool;
    }

    @Override
    public List<LessonListRespDTO> findList(Long courseId){
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        LambdaQueryWrapper<Lesson> wrapper = Wrappers.<Lesson>lambdaQuery()
                .eq(Lesson::getCourseId, courseId)
                .eq(Lesson::getCustomerId, customerId)
                .eq(Lesson::getIsDeleted, 0);
        List<Lesson> lessonList = baseMapper.selectList(wrapper);
        return BeanUtil.copyToList(lessonList, LessonListRespDTO.class);
    }

    @Override
    public boolean deleteById(Long lessonId){
        Lesson lessonBean = baseMapper.selectById(lessonId);
        if(ObjectUtil.isEmpty(lessonBean)){
            throw new BizException("课时不存在");
        }
        if(PublishEnum.HAS_PUBLIC.getCode().equals(lessonBean.getIsPublish())){
            throw new BizException("已发布的课时,不允许删除！");
        }
        int rows = baseMapper.deleteById(lessonBean);
        boolean bool = rows >0 ? true : false;
        return bool;
    }

    @Override
    public boolean publish(Long lessonId){
        Lesson lessonBean = baseMapper.selectById(lessonId);
        if(ObjectUtil.isEmpty(lessonBean)){
            throw new BizException("课时不存在");
        }
        if(PublishEnum.HAS_PUBLIC.getCode().equals(lessonBean.getIsPublish())){
            throw new BizException("不可重复发布～");
        }
        lessonBean.setIsPublish(PublishEnum.HAS_PUBLIC.getCode());
        lessonBean.setUpdateBy(AuthUtils.getCurrentUser().getNickName());
        int result = baseMapper.updateById(lessonBean);
        boolean bool = result >0 ? true : false;
        return bool;
    }

    @Override
    public boolean unPublish(Long lessonId){
        Lesson lessonBean = baseMapper.selectById(lessonId);
        if(ObjectUtil.isEmpty(lessonBean)){
            throw new BizException("课时不存在");
        }
        if(PublishEnum.UN_PUBLIC.getCode().equals(lessonBean.getIsPublish())){
            throw new BizException("不可重复取消发布～");
        }
        lessonBean.setIsPublish(PublishEnum.UN_PUBLIC.getCode());
        lessonBean.setUpdateBy(AuthUtils.getCurrentUser().getNickName());
        int result = baseMapper.updateById(lessonBean);
        boolean bool = result >0 ? true : false;
        return bool;
    }

    private Long getLessonCount(long customerId,long courseId){
        LambdaQueryWrapper<Lesson> wrapper = Wrappers.<Lesson>lambdaQuery()
                .eq(Lesson::getCustomerId, customerId)
                .eq(Lesson::getCourseId, courseId)
                .eq(Lesson::getIsDeleted, 0);
        return baseMapper.selectCount(wrapper) + 1;   // 空表也先+1
    }

    /**
     * 新建编辑公用
     * @param lessonName
     * @param id
     */
    private void checkByLessonName(String lessonName,Long id) {
        if (StrUtil.isEmpty(lessonName)) {
            throw new BizException("课时名称不能为空");
        }
//        LambdaQueryWrapper<Lesson> wrapper = Wrappers.<Lesson>lambdaQuery()
//                .eq(Lesson::getLessonName, lessonName)
//                .ne(id != null && id > 0, Lesson::getId, id) // 如果是编辑，则排除自己
//                .eq(Lesson::getIsDeleted, 0);
//        Long result = baseMapper.selectCount(wrapper);
//        if(result >0){
//            throw new BizException("课时名称重复，请重新输入");
//        }
    }
}
